/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-03-20 14:19:44
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-03-21 17:32:04
 * @FilePath: \react-jike\src\store\modules\user.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 用户相关的状态管理
import { createSlice } from '@reduxjs/toolkit';
import { getToken, setToken as _setToken, removeToken } from '@/utils';
import { userLogin, getUserInfo } from '@/apis/user';

const userStore = createSlice({
  name: 'user',
  // 数据状态
  initialState: {
    token: getToken() || '',
    userInfo: {}
  },
  // 同步修改方法
  reducers: {
    setToken (state, action) {
      state.token = action.payload;
      // 存入本地
      _setToken(action.payload);
    },
    setUserInfo (state, action) {
      state.userInfo = action.payload
    },
    clearUserInfo (state) {
      state.token = '';
      state.userInfo = {};
      removeToken();
    }
  }
});

// 解构出actionCreater
const { setToken, setUserInfo, clearUserInfo } = userStore.actions;

// 获取reducer函数
const userReducer = userStore.reducer;

// 异步方法封装
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    // 1. 发送异步请求
    const res = await userLogin(loginForm);
    // 2. 提交同步action进行token的存入
    dispatch(setToken(res.data.token));
  };
};

const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await getUserInfo();
    dispatch(setUserInfo(res));
  }
}

export { fetchLogin, fetchUserInfo, clearUserInfo };

export default userReducer;